package com.zx.map.controller.timer;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.zx.map.dao.BaseAcctInfoDao;
import com.zx.map.dao.model.BaseAcctInfo;
import com.zx.map.service.EncashLogService;
import com.zx.map.service.RemoteIntefaceVisitService;
import com.zx.map.service.model.EncashLogModel;
import com.zx.map.service.model.OutcomeResponse;
import com.zx.mobile.MobileCommonHelper;
import com.zx.mobile.PayRateHelper;
import com.zx.platform.utils.DateUtils;

/**
 * T1出款批次
 *
 * @author Administrator
 */
public class MainTimerController {
	/**
	 * log
	 */
	private static Logger log = Logger.getLogger(MainTimerController.class);
	@Autowired
	private EncashLogService encashLogService;
	@Autowired
	private RemoteIntefaceVisitService remoteIntefaceVisitService;
	@Autowired
	private BaseAcctInfoDao baseAcctInfoDao;

	/**
	 * 批量结算 招行银企直连 始终确保每笔订单只被处理一次 不管是否成功 任务调度初始将 筛选记录更新为运行中状态 待处理结束后更新为终态
	 */
	public void batchOutcomeByCMB() {
		try {
			log.info("批量结算出款开始时间，" + new Date());
			// 处理上一日 T+1出款
			EncashLogModel encashParam = new EncashLogModel();
			encashParam.setEncashDay(DateUtils.dateToString(DateUtils.addDate(new Date(), -1), "yyyyMMdd"));// 上一自然日
			encashParam.setEncashType(MobileCommonHelper.ENCASHTYPE_T1);
			encashParam.setEncashStatus(MobileCommonHelper.OUTCOMESTATUS_NORMAL);
			List<EncashLogModel> encashLogModelList = new ArrayList<EncashLogModel>();
			encashLogModelList.addAll(encashLogService.getListByModel(encashParam));
			encashParam = new EncashLogModel();
			encashParam.setEncashDay(DateUtils.dateToString(DateUtils.addDate(new Date(), -3), "yyyyMMdd"));// 上一自然日
			encashParam.setEncashType(MobileCommonHelper.ENCASHTYPE_T1);
			encashParam.setEncashStatus(MobileCommonHelper.OUTCOMESTATUS_NORMAL);
			encashLogModelList.addAll(encashLogService.getListByModel(encashParam));

			// 更新筛选内容处理状态为处理中
			EncashLogModel encashDeal = new EncashLogModel();
			encashDeal.setEncashStatus(MobileCommonHelper.OUTCOMESTATUS_PROCESS);
			encashLogService.updateEncashLogBySelect(encashDeal, encashParam);
			// 获取总记录数 按批次逐一提交 默认批次大小 50
			int listSize = encashLogModelList.size();
			log.info("批量结算出款开始：总记录，" + listSize);
			for (EncashLogModel en : encashLogModelList) {
				BaseAcctInfo baseAcct = baseAcctInfoDao.selectByPrimaryKey(en.getMerchantId());
				BigDecimal encachAmt = new BigDecimal(en.getEncashAmt().toString());
				baseAcct.setAcctBal(baseAcct.getAcctBal() - encachAmt.doubleValue());
				baseAcctInfoDao.update(baseAcct);

				// 2元的代付费调整统一都收（原来是5000以下客户自己承担，5000以上我们承担）；edit by wenjw 2017.1.9
				// if (encachAmt.compareTo(new BigDecimal(PayRateHelper.ENCASHLIMITAMT)) <= 0) {
				BigDecimal remainAmt = encachAmt.subtract(new BigDecimal(PayRateHelper.ENCASHAMTPER)).setScale(2,
						BigDecimal.ROUND_HALF_UP);
				en.setSettleAmt(remainAmt.doubleValue());// 设置结算金额
				/*
				 * } else { en.setSettleAmt(en.getEncashAmt());//设置结算金额 为取现金额 }
				 */
				// 由于部分取现申请 经过扣费后 出现负数情况 排除此类批量结算数据
				if (en.getSettleAmt() < 0) {
					// 并对数据进行保存
					en.setSettleRemark("该笔结算金额太小 不需要结算");
					en.setSettleTime(DateUtils.dateToString(new Date(), "yyyyMMddHHmmss"));
					en.setSettleStatus(MobileCommonHelper.OUTCOMESTATUS_SUCCESS);
					en.setEncashStatus(MobileCommonHelper.OUTCOMESTATUS_SUCCESS);
					encashLogService.update(en);
				} else {
					OutcomeResponse response = remoteIntefaceVisitService.outComeSingleByCmb(
							en.getSettleAmt().toString(), en.getEncashId(), en.getSettleCardInfoModel());
					en.setSettleOrdId(response.getSettleOrdId());
					en.setSettleTime(DateUtils.dateToString(new Date(), "yyyyMMddHHmmss"));
					en.setSettleRemark(response.getReturnCode() + response.getErrMsg());
					if ("0000".equals(response.getReturnCode())) {
						en.setSettleStatus(MobileCommonHelper.OUTCOMESTATUS_SUCCESS);
						en.setEncashStatus(MobileCommonHelper.OUTCOMESTATUS_SUCCESS);
					} else {
						en.setSettleStatus(MobileCommonHelper.OUTCOMESTATUS_FAIL);
						en.setEncashStatus(MobileCommonHelper.OUTCOMESTATUS_FAIL);
					}
					encashLogService.update(en);
				}
			}
			log.info("批量结算出款结束时间" + new Date());
		} catch (Exception e) {
			log.error("批处理异常", e);
		}
	}

	/**
	 * 批量结算通联 始终确保每笔订单只被处理一次 不管是否成功 任务调度初始将 筛选记录更新为运行中状态 待处理结束后更新为终态
	 */
	public void batchOutcome() {
		try {
			log.info("批量结算出款开始时间，" + new Date());
			// 处理上一日 T+1出款
			EncashLogModel encashParam = new EncashLogModel();
			encashParam.setEncashDay(DateUtils.dateToString(DateUtils.addDate(new Date(), -1), "yyyyMMdd"));// 上一自然日
			encashParam.setEncashType(MobileCommonHelper.ENCASHTYPE_T1);
			encashParam.setEncashStatus(MobileCommonHelper.OUTCOMESTATUS_NORMAL);
			List<EncashLogModel> encashLogModelList = encashLogService.getListByModel(encashParam);

			// 更新筛选内容处理状态为P
			EncashLogModel encashDeal = new EncashLogModel();
			encashDeal.setEncashStatus(MobileCommonHelper.OUTCOMESTATUS_PROCESS);
			encashLogService.updateEncashLogBySelect(encashDeal, encashParam);
			// 获取总记录数 按批次逐一提交 默认批次大小 50
			int listSize = encashLogModelList.size();
			log.info("批量结算出款开始：总记录，" + listSize);
			if (listSize > 0) {
				int batchTime = listSize / 50 + 1;
				log.info("批量结算出款总批次," + batchTime);
				for (int i = 0; i < batchTime; i++) {
					log.info("批量结算出款第" + i + 1 + "批次开始");
					int begin = i * 50;
					int end = begin + 50;
					if (i + 1 == batchTime) {
						end = listSize;
					}
					List<EncashLogModel> temp = encashLogModelList.subList(begin, end);
					// 计算出款金额
					Iterator<EncashLogModel> iterator = temp.iterator();
					while (iterator.hasNext()) {
						EncashLogModel en = (EncashLogModel) iterator.next();
						BigDecimal encachAmt = new BigDecimal(en.getEncashAmt().toString());
						// 2元的代付费调整统一都收（原来是5000以下客户自己承担，5000以上我们承担）；edit by wenjw 2017.1.9
						// if (encachAmt.compareTo(new BigDecimal(PayRateHelper.ENCASHLIMITAMT)) <= 0) {
						BigDecimal remainAmt = encachAmt.subtract(new BigDecimal(PayRateHelper.ENCASHAMTPER))
								.setScale(2, BigDecimal.ROUND_HALF_UP);
						en.setSettleAmt(remainAmt.doubleValue());// 设置结算金额
						/*
						 * } else { en.setSettleAmt(en.getEncashAmt());//设置结算金额 为取现金额 }
						 */

						// 由于部分取现申请 经过扣费后 出现负数情况 排除此类批量结算数据
						if (en.getSettleAmt() < 0) {
							// 将该笔从待结算list剔除
							iterator.remove();
							// 并对数据进行保存
							en.setSettleRemark("该笔结算金额太小 不需要结算");
							en.setSettleTime(DateUtils.dateToString(new Date(), "yyyyMMddHHmmss"));
							en.setSettleStatus(MobileCommonHelper.OUTCOMESTATUS_SUCCESS);
							en.setEncashStatus(MobileCommonHelper.OUTCOMESTATUS_SUCCESS);
							encashLogService.update(en);
						}
					}

					List<EncashLogModel> encashLogModels = remoteIntefaceVisitService.outComeBatch(temp);
					for (EncashLogModel oo : encashLogModels) {
						encashLogService.update(oo);
					}
					log.info("批量结算出款第" + i + 1 + "批次结束");
				}
			}
			log.info("批量结算出款结束时间" + new Date());

		} catch (Exception e) {
			log.error("批处理异常", e);
		}
	}
}
